<template>
  <div>
    <component v-if="loaded" :is="loaded" ref='child' 
      :appKey="appKey" :compName="compName"
      :value="value" @input="onInput" v-bind="$attrs" v-on="$listeners" />
    <loading v-else :appKey="appKey" :compName="compName" />
  </div>
</template>

<script>
  import { __SHARE_INSTALL__ } from '@/utils/share'
  import loading from './common/loading'
  export default {
    name: "Wrapper",
    inheritAttrs: false,
    components: { loading },
    props: {
      // v-model值，传递给业务组件
      value: {
      },
      // 共享组件所在的应用
      appKey: {
        type: String,
        required: true
      },
      // 共享组件组件名
      compName: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        loaded: null,   // 组件加载成功标志
      }
    },
    created() {
      this.initEmit()

      this.loadComponent()
    },
    mounted() {
      
    },
    methods: {
      onInput(val) {
        if(this.value != val) {
          this.$emit('input', val)
        }
      },
      initEmit() {
        const orginalEmit = this.$emit
        this.$emit = function(event, ...args) {
          if(event =='input' || event.startsWith('hook:')) {
            // input事件调用原来的函数
            orginalEmit.call(this, event, ...args)
          } else {
            // 接收事件后传递给子组件
            this.$refs.child.$emit(event, ...args)
          }
        }
      },
      async loadComponent() {
        this.loaded = await __SHARE_INSTALL__(this.appKey, this.compName)
      }
    }
  }
</script>

<style scoped lang="scss">

</style>
